package com.fyzk.activity.user;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.App;
import com.fyzk.activity.app.AppToast;
import com.fyzk.base.BaseActivity;
import com.fyzk.bean.RegisteResponse;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.model.UMengTongJi_eventIds;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.net.http.NetWork;
import com.fyzk.view.TopTitleView;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

/**
 * 用户注册界面
 */
public class RegisteActivity extends BaseActivity {

    private TopTitleView zhuce_top_rl;
    private EditText center_pwd;

    private EditText center_cellPhone;
    private EditText center_yanZhengMa;
    private EditText center_inviteCode;

    public static TextView center_chongFa;
    private LinearLayout center_ll_checkBox;
    private CheckBox center_checkBox;
    private TextView center_xieYi;
    private TextView center_zhuCe;

    private List<String> users = new ArrayList<String>();

    private ZhuCeOnClick zhuCeOnClick;

    private boolean isAgree = true;

    private static final int DAOJISHI = 60;
    public static int daojs_yzm = DAOJISHI;
    private Handler handler_yzm;
    private Runnable runnable_yzm;

    private int registerType = 1;   // 1手机号注册 2用户名注册

    private CheckBox userName_cb;
    private EditText userName_et;
    private LinearLayout userName_til;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_register);
        // 消除网络异常
        NetWork.netWork();
        // 单击事件
        zhuCeOnClick = new ZhuCeOnClick();
        // 控件初始化
        info();
        users = getUsers();
        handler_yzm = new Handler();
        runnable_yzm = new Runnable() {

            @Override
            public void run() {
                djs_yzm();
            }
        };
        String phone = getIntent().getStringExtra("phone");
        if(!TextUtil.isEmpty(phone)){
            center_cellPhone.setText(phone);
        }
    }

    RegisteResponse registeResponse;

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.USER_REGISTERED:
                UMengTongJi_eventIds.RegistrationOnClick(this);
                AppToast.getToast().show("注册成功");
                registeResponse = JSON.parseObject(resultBean.getData(), RegisteResponse.class);
                MySharedPreferences.getInstance().setLoginStatus(true);
                MySharedPreferences.getInstance().setUserNo(registeResponse.getUserno());
                MySharedPreferences.getInstance().setUserName(registeResponse.getUsername());
                MySharedPreferences.getInstance().setAlias(registeResponse.getAlias());
                MySharedPreferences.getInstance().setAuthToken(registeResponse.getAccessToken());
                MySharedPreferences.getInstance().setBalance(PublicMethod.formatBalance
                        (Double.parseDouble(registeResponse.getBalance())));
                MySharedPreferences.getInstance().setDrawbalance(PublicMethod.formatBalance
                        (Double.parseDouble(registeResponse.getDrawbalance())));
                MySharedPreferences.getInstance().setPhotoUrl(registeResponse.getPhotoUrl());
                finish();
                break;
            case CommandUtil.PHONE_VERIFICATION:
                AppToast.getToast().show("获取验证码成功");
                daojs_yzm = DAOJISHI - 1;
                center_chongFa.setClickable(false);
                center_chongFa.setText(daojs_yzm + "秒\n后重发");
                handler_yzm.post(runnable_yzm);
                break;
            case CommandUtil.USERNAMEVALIDATE:
                break;
        }
    }

    private void register() {

        try {
            JSONObject request_json = new JSONObject();
            request_json.put("phone", center_cellPhone.getText().toString());
            if (registerType == 1) {
                request_json.put("username", center_cellPhone.getText().toString());
            } else {
                request_json.put("username", userName_et.getText().toString());
            }
            request_json.put("password", center_pwd.getText().toString());
            request_json.put("validateCode", center_yanZhengMa.getText().toString());
            request_json.put("invitationCode", center_inviteCode.getText().toString());
            request_json.put("registerType", registerType);
            request_json.put("userAgent", App.getChannel());
            httpPostJson(CommandUtil.USER_REGISTERED, Commands.NEWREGISTER, request_json, true);

        } catch (JSONException e) {

        }
    }

    @Override
    protected void onFailure(int requestCode, String errorCode, String message) {
        cancelProgressDialog();
        switch (requestCode) {
            case CommandUtil.USER_REGISTERED:
                showToast(message);
                break;
            case CommandUtil.PHONE_VERIFICATION:
                showToast(message);
                break;
            case CommandUtil.USERNAMEVALIDATE:
                break;
        }

    }

    /**
     * 获取短信验证码
     */
    private void getYanZhengMa() {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("mobilePhone", center_cellPhone.getText().toString());
            request_json.put("username", center_cellPhone.getText().toString());
            httpPostJson(CommandUtil.PHONE_VERIFICATION, Commands.PHONE_VERIFICATION_NEW,
                    request_json, true);
        } catch (JSONException e) {

        }
    }

    private void actionProtocol(boolean isAgree) {
        this.isAgree = isAgree;
        center_checkBox.setChecked(isAgree);
    }

    boolean hasSended = false;

    /**
     * 控件初始化
     */
    private void info() {
        //根据路径得到Typeface
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/pingfang.ttf");
        // 顶部
        zhuce_top_rl = (TopTitleView) findViewById(R.id.zhuce_top_rl);

        // 中间 center
        center_pwd = (EditText) findViewById(R.id.zhuce_et_pwd);
        center_pwd.setTypeface(tf);
        center_cellPhone = (EditText) findViewById(R.id.zhuce_et_cellphone);
        center_cellPhone.setTypeface(tf);
        center_yanZhengMa = (EditText) findViewById(R.id.zhuce_et_yanzhengma);
        center_yanZhengMa.setTypeface(tf);
        center_inviteCode = (EditText) findViewById(R.id.zhuce_et_invite);
        center_inviteCode.setTypeface(tf);
        center_chongFa = (TextView) findViewById(R.id.zhuce_center_tv_chongfa);
        center_chongFa.setTypeface(tf);
        if (daojs_yzm == 0 || daojs_yzm == DAOJISHI) {
            center_chongFa.setClickable(true);
//            center_chongFa.setTextColor(Color.WHITE);
            if (!hasSended) {
                center_chongFa.setText(R.string.zhuce_center_fa);
            } else {
                center_chongFa.setText(R.string.zhuce_center_chongfa);
            }
            daojs_yzm = DAOJISHI;
        } else {
            hasSended = true;
//            center_chongFa.setTextColor(Color.GRAY);
            center_chongFa.setClickable(false);
            center_chongFa.setText(daojs_yzm + "秒后可重发");
        }

        center_xieYi = (TextView) findViewById(R.id.zhuce_center_tv_xieyi);
        center_xieYi.setTypeface(tf);
        center_zhuCe = (TextView) findViewById(R.id.zhuce_center_tv_zhuce);
        center_zhuCe.setTypeface(tf);
        center_ll_checkBox = (LinearLayout) findViewById(R.id.zhuce_center_ll_checkbox);
        center_checkBox = (CheckBox) findViewById(R.id.zhuce_center_iv_checkbox);

        center_checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isAgree = isChecked;
                if (isChecked == true) {
                    center_zhuCe.setClickable(true);
                } else {
                    center_zhuCe.setClickable(false);
                }
            }
        });

		/* 事件 */
        // 顶部
        zhuce_top_rl.setOnTitleClickListener(this);

        // 中间 center 事件
        center_chongFa.setOnClickListener(zhuCeOnClick);
        center_ll_checkBox.setOnClickListener(zhuCeOnClick);
        center_xieYi.setOnClickListener(zhuCeOnClick);
        center_zhuCe.setOnClickListener(zhuCeOnClick);

        // 用户名
        userName_cb = (CheckBox) findViewById(R.id.register_username_cb);
        userName_et = (EditText) findViewById(R.id.register_username_et);
        userName_til = (LinearLayout) findViewById(R.id.register_username_til);

        userName_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    registerType = 2;   // 用户名注册
                    userName_til.setVisibility(View.VISIBLE);
                } else {
                    registerType = 1;   // 手机号注册
                    userName_til.setVisibility(View.GONE);
                }
            }
        });

        userName_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return event.getKeyCode() == KeyEvent.KEYCODE_ENTER;    // 禁止输入回车
            }
        });
    }

    /**
     * 验证码 有效倒计时
     */
    private void djs_yzm() {
        handler_yzm.postDelayed(runnable_yzm, 1000);
        if (daojs_yzm == 0 || daojs_yzm == DAOJISHI) {
            handler_yzm.removeCallbacks(runnable_yzm);
            center_chongFa.setClickable(true);
//            center_chongFa.setTextColor(Color.WHITE);
            if (!hasSended) {
                center_chongFa.setText(R.string.zhuce_center_fa);
            } else {
                center_chongFa.setText(R.string.zhuce_center_chongfa);
            }
            daojs_yzm = DAOJISHI;
        } else {
            hasSended = true;
//            center_chongFa.setTextColor(Color.WHITE);
            center_chongFa.setClickable(false);
            center_chongFa.setText(daojs_yzm + "秒后可重发");
            daojs_yzm -= 1;
        }
    }

    /**
     * 输入框验证
     *
     * @return
     */
    private boolean et_yanZheng() {
        // 检测手机号
        if (!phone_yanZheng()) {
            return false;
        }

        if (TextUtil.isEmpty(center_yanZhengMa.getText().toString())) {
            center_yanZhengMa.setError("验证码不能为空！");
            showToast("验证码不能为空！");
            return false;
        }
        if (TextUtil.isEmpty(center_pwd.getText().toString())) {
            center_pwd.setError("密码不能为空！");
            showToast("密码不能为空！");
            return false;
        }
        if (!Pattern.matches("[a-zA-Z0-9]{6,15}$", center_pwd.getText().toString())) {
            center_pwd.setError("密码由6~15位字母、数字组成！");
            showToast("密码由6~15位字母、数字组成！");
            center_pwd.requestFocus();
            center_pwd.setSelectAllOnFocus(true);
            return false;
        }

        if (TextUtil.isEmpty(center_inviteCode.getText().toString())) {
            center_inviteCode.setError("邀请码不能为空！");
            showToast("邀请码不能为空！");
            return false;
        }
        if (!Pattern.matches("[a-zA-Z0-9]+", center_inviteCode.getText().toString())) {
            center_inviteCode.setError("邀请码由字母、数字组成！");
            showToast("邀请码由字母、数字组成！");
            center_inviteCode.requestFocus();
            center_inviteCode.setSelectAllOnFocus(true);
            return false;
        }

        if (registerType == 2) {
            if (TextUtil.isEmpty(userName_et.getText().toString())) {
                center_yanZhengMa.setError("用户名不能为空！");
                showToast("用户名不能为空！");
                return false;
            }
            if (Pattern.matches("[0-9]{4,16}$", userName_et.getText().toString())) {
                userName_et.setError("用户名不能是纯数字！");
                showToast("用户名不能是纯数字！");
                userName_et.requestFocus();
                userName_et.setSelectAllOnFocus(true);
                return false;
            }
            if (!Pattern.matches("[a-zA-Z0-9\\u4e00-\\u9fa5]{4,16}$", userName_et.getText().toString())) {
                userName_et.setError("用户名由4~16位字母、数字或汉字组成！");
                showToast("用户名由4~16位字母、数字或汉字组成！");
                userName_et.requestFocus();
                userName_et.setSelectAllOnFocus(true);
                return false;
            }
        }

        return true;
    }

    /**
     * 检测手机号
     *
     * @return
     */
    private boolean phone_yanZheng() {
        clear_focus();
        // 检测手机号
        if (center_cellPhone.getText().toString().length()!=11) {
            center_cellPhone.setError("手机号码格式不正确！");
            showToast("手机号码格式不正确！");
            center_cellPhone.requestFocus();
            center_cellPhone.setSelectAllOnFocus(true);
            return false;
        }

        return true;
    }

    private void clear_focus() {
        center_pwd.clearFocus();
        center_cellPhone.clearFocus();
        center_yanZhengMa.clearFocus();
    }


    /**
     * 读取首选项中 用户名
     */
    private List<String> getUsers() {
        String userStrings[];
        String userString = MySharedPreferences.getInstance().getUserNames();
        if (!userString.equals("")) {
            userStrings = userString.split(",");
            for (int i = 0; i < userStrings.length; i++) {
                users.add(userStrings[i].toString());
            }
        } else {
            userStrings = null;
        }
        return users;
    }

    private AlertDialog forgetPswDialog = null;


    /**
     * 单击事件
     * @author Administrator
     */
    class ZhuCeOnClick implements OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.zhuce_center_tv_chongfa:
                    if (phone_yanZheng()) {
                        getYanZhengMa();
                    }
                    break;
                case R.id.zhuce_center_tv_xieyi:
                    if (forgetPswDialog == null) {
                        View view = View.inflate(RegisteActivity.this, R.layout.zhuce_xieyi, null);
                        TextView neiRong = (TextView) view.findViewById(R.id.dialog_neirong);
                        InputStream inputStream = getResources().openRawResource(R.raw.xieyi);
                        neiRong.setText(PublicMethod.getStringFromStream(inputStream));

                        forgetPswDialog = new AlertDialog.Builder(RegisteActivity.this).setView
                                (view).setTitle("乐彩竞猜彩票注册协议").setPositiveButton("同意", new
                                DialogInterface.OnClickListener() {


                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        actionProtocol(true);
                                    }
                                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                actionProtocol(false);
                            }
                        }).create();

                    }

                    forgetPswDialog.show();


                    break;
                case R.id.zhuce_center_tv_zhuce:
                    if (et_yanZheng()) {
                        if (isAgree) {
                            register();
                        }
                    }
                    break;

                default:
                    break;
            }
        }

    }

}